package com.advertisementsystem.Controller;

import com.advertisementsystem.Servie.StatisticsService;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.vo.AdStatisticsExportVO;
import com.advertisementsystem.vo.DeviceStatisticsExportVO;
import com.advertisementsystem.vo.OverallStatisticsExportVO;
import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/statistics")
@Slf4j
public class StatisticsController {

    @Autowired
    private StatisticsService statisticsService;

    // 获取广告统计数据
    @GetMapping("/advertisement/{adId}")
    @PreAuthorize("hasAnyRole('ADMIN', 'ADVERTISER')")
    public ResponseResult<Map<String, Object>> getAdvertisementStatistics(
            @PathVariable Long adId) {
        return ResponseResult.success(statisticsService.getAdvertisementStatistics(adId));
    }

    // 获取设备统计数据
    @GetMapping("/device/{deviceId}")
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVICE_OWNER')")
    public ResponseResult<Map<String, Object>> getDeviceStatistics(
            @PathVariable Long deviceId) {
        return ResponseResult.success(statisticsService.getDeviceStatistics(deviceId));
    }

    // 获取整体统计数据
    @GetMapping("/overall")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<Map<String, Object>> getOverallStatistics(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        return ResponseResult.success(statisticsService.getOverallStatistics(startDate, endDate));
    }

    // 导出广告统计数据
    @GetMapping("/advertisement/{adId}/export")
    @PreAuthorize("hasAnyRole('ADMIN', 'ADVERTISER')")
    public void exportAdvertisementStatistics(
            @PathVariable Long adId,
            HttpServletResponse response) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("广告统计数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 获取统计数据
            Map<String, Object> statistics = statisticsService.getAdvertisementStatistics(adId);

            // 准备数据
            List<Map<String, Object>> dailyStats = (List<Map<String, Object>>) statistics.get("dailyStats");
            List<AdStatisticsExportVO> exportData = dailyStats.stream().map(stat -> {
                AdStatisticsExportVO vo = new AdStatisticsExportVO();
                vo.setDate((String) stat.get("date"));
                vo.setPlayCount((Integer) stat.get("play_count"));
                vo.setViewCount((Integer) stat.get("view_count"));
                vo.setViewRate(calculateViewRate((Integer) stat.get("play_count"),
                        (Integer) stat.get("view_count")));
                return vo;
            }).collect(Collectors.toList());

            // 导出数据
            EasyExcel.write(response.getOutputStream(), AdStatisticsExportVO.class)
                    .sheet("广告统计")
                    .doWrite(exportData);

        } catch (Exception e) {
            log.error("导出广告统计数据失败", e);
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }

    // 导出设备统计数据

    // 导出整体统计数据
    @GetMapping("/overall/export")
    @PreAuthorize("hasRole('ADMIN')")
    public void exportOverallStatistics(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            HttpServletResponse response) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("整体统计数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 获取统计数据
            Map<String, Object> statistics = statisticsService.getOverallStatistics(startDate, endDate);

            // 准备数据
            List<Map<String, Object>> dailyStats = (List<Map<String, Object>>) statistics.get("dailyStats");
            List<OverallStatisticsExportVO> exportData = dailyStats.stream().map(stat -> {
                OverallStatisticsExportVO vo = new OverallStatisticsExportVO();
                vo.setDate((String) stat.get("date"));
                vo.setAdCount((Integer) stat.get("ad_count"));
                vo.setDeviceCount((Integer) stat.get("device_count"));
                vo.setPlayCount((Integer) stat.get("play_count"));
                vo.setViewCount((Integer) stat.get("view_count"));
                vo.setViewRate(calculateViewRate((Integer) stat.get("play_count"),
                        (Integer) stat.get("view_count")));
                return vo;
            }).collect(Collectors.toList());

            // 导出数据
            EasyExcel.write(response.getOutputStream(), OverallStatisticsExportVO.class)
                    .sheet("整体统计")
                    .doWrite(exportData);
        } catch (Exception e) {
            log.error("导出整体统计数据失败", e);
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }
    // 计算观看率
    private String calculateViewRate(Integer playCount, Integer viewCount) {
        if (playCount == null || playCount == 0) {
            return "0%";
        }
        double rate = (double) viewCount / playCount * 100;
        return String.format("%.2f%%", rate);
    }
}